import axios from 'axios'
import store from '@/store'
import router from '@/router/index'
// import { MessageBox, Message } from 'element-ui'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截
service.interceptors.request.use(
  config => {
    // console.log('请求拦截', store.state.user)
    const token = store.state.user.token
    if (token) {
      // config.headers['token'] = token
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    if (response.data.success) {
      // console.log('响应拦截', response.data)
      return response.data
    } else {
      return Promise.reject('请求失败')
    }
  },
  error => {
    // console.dir(error)
    if (error.response.data.code === 10002) {
      console.log('token失效')
      store.dispatch('user/userLogout')
      router.push('/login?return_url=' + encodeURIComponent(router.currentRoute.fullPath))
    }
    return Promise.reject(error)
  }
)

export default service
